package com.hearwego;

import java.util.List;

import com.utilities.HWGSQLiteHelper;
import com.utilities.Informacion;
import com.utilities.RssParserPull;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;

public class LocationListFragment extends ListFragment {
	
	static List<Informacion> informacion;
	public LocationModel[] getAudioList;
	static ProgressDialog dialog;
	static Activity activity;
    HWGSQLiteHelper usdbh;
    SQLiteDatabase db;
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    int actualId;
    String audio_subtitulo,audio_archivo; 
    boolean resultAudio=false;
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        preferences= getActivity().getSharedPreferences("Preferencias",Context.MODE_PRIVATE);
        editor = preferences.edit();
        actualId = preferences.getInt("actualid", 0);
        
        usdbh =new HWGSQLiteHelper(getActivity(), "DBHWG", null, 1);
        db = usdbh.getWritableDatabase();
        
        activity = getActivity();
    	Cursor c = db.rawQuery("SELECT * FROM Audio", null);

//    	Cursor c = db.rawQuery("SELECT * FROM Audio", null);

         if (c.getCount() < 1){
         	new getAudioList().execute("");
         }else{
             new LoagGastos().execute("");

         }
      	Log.i("Column Counts", ""+c.getColumnCount());

    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Activity activity = getActivity();
        if (activity != null) {   
            ListAdapter listAdapter = getListAdapter();
            LocationModel locationModel = (LocationModel) listAdapter.getItem(position);
            
            String url = locationModel.archivo; // your URL here
        }
    }
    
    
    public class getAudioList extends AsyncTask<String, String, String>{

    	@Override
    	protected void onPreExecute() {
    		super.onPreExecute();
			dialog = ProgressDialog.show(activity, "","Cargando. Por favor espere...", true);

    	}
    	
		@Override
		protected String doInBackground(String... arg0) {
			RssParserPull parse = new RssParserPull("http://www.smartthinking.com.mx:8080/HearWeGo/DataServlet?Query=select%20*%20from%20audios%20where%20poi_idr%20="+actualId+"&BaseDatos=hwg");
			informacion = null;
			informacion = parse.parse();
			
            if(db != null)
            {
              for(int i=0; i < informacion.size();i++){
                      db.execSQL("INSERT INTO Audio (audio_subtitulo, audio_archivo) " +
                               "VALUES ('" +informacion.get(i).getAudioSubtitulo()+"', '"+informacion.get(i).getAudio()+"')");
//              		resultAudio = true;
              } 
      		db.close();

            }
            	
                    return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			
//            Toast.makeText(getActivity().getApplicationContext(), "Descripcion Agregada", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
            dialog.cancel();
            new LoagGastos().execute("");
			

		}
    	
    }
    
    public class LoagGastos extends AsyncTask<String, String, String>{
        int zeroGastos = -1;
        
        @Override
                protected void onPreExecute() {
                        super.onPreExecute();
                }
        
            @Override
            protected String doInBackground(String... params) {
            usdbh =new HWGSQLiteHelper(getActivity(), "DBHWG", null, 1);
            db = usdbh.getWritableDatabase();
            if(db != null )
            {
                    Cursor c = db.rawQuery("SELECT * FROM Audio", null);
                    if (c.moveToFirst()) {
                            zeroGastos = 1;
                            
                            audio_subtitulo = c.getString(1);
                            audio_archivo = c.getString(2);
                            
                            Log.i("BD", audio_subtitulo + audio_archivo);
                    }else{
                            zeroGastos = 0;
                    }
                    db.close();
            }
                    return null;
            }
            
            @Override
            protected void onPostExecute(String result) {
                    super.onPostExecute(result);
                  
                    if(!(informacion.size() < 1) ){
	        			if(! (audio_archivo.equals("") || audio_archivo.equals("null")) ){
			        			 LocationModel[] sLocations = { 
			        			        new LocationModel(audio_subtitulo, audio_archivo)
			        			    };
			        			 
			        			 getAudioList = sLocations;
			        			 Log.i("Audios", ""+getAudioList.length);
			        		        if (activity != null) {
			        		            ListAdapter listAdapter = new LocationModelListAdapter(activity, getAudioList);
			        		            setListAdapter(listAdapter);
			        		        }
			        		        
	        			}
                    }
            else{
                    	ListAdapter listAdapter = new LocationModelListAdapter(activity, null);
     		            setListAdapter(listAdapter);
                    }
    				
            }
        
}        
}
